//
//  TButton.swift
//  TalkeApp
//
//  Created by lhf on 2024/3/8.
//

import Foundation
import UIKit

class TVcodeButton: UIButton {

    fileprivate var hg_timer: Timer?
    fileprivate var hg_remindTime: NSInteger?
    
    func timeDown(time: NSInteger) {
        isEnabled = false
        hg_remindTime = time
        if #available(iOS 10.0, *) {
            hg_timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
                self.timeFire()
            })
        } else {
            // Fallback on earlier versions
            hg_timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timeFire), userInfo: nil, repeats: true)
        }
    }
    
    @objc fileprivate func timeFire() {
        if hg_remindTime! > 1 {
            hg_remindTime! -= 1
            setTitle("重新发送(\(hg_remindTime!))", for: .disabled)
            setTitleColor(AppConfig.sharedInstance.MAIN_COLOR, for: .disabled)
            isEnabled = false
        } else {
            isEnabled = true
            hg_timer?.invalidate()
            hg_timer = nil
            setTitle("获取验证码", for: .normal)
            setTitle("重新发送(\(AppConfig.sharedInstance.vcodeInterval))", for: .disabled)
        }
    }
}

@IBDesignable class TButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame:frame)
        normalInit()
        
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        normalInit()
        
    }
    override func prepareForInterfaceBuilder() {
        normalInit()
        
    }
    private func normalInit() {
        self.setTitle("", for: .highlighted)
    }
}

class TDisableButton: TButton {
    func changeDisableStatus(_ status: Bool) {
        self.isEnabled = status
        self.backgroundColor = status ? AppConfig.sharedInstance.MAIN_COLOR : AppConfig.sharedInstance.MAIN_COLOR.alpha(0.5)
        self.setTitleColor(status ? AppConfig.sharedInstance.whiteColor : AppConfig.sharedInstance.whiteColor.alpha(0.5), for: .normal)
    }
}
